package com.wxsoft.java.proxy.cglib.demo;

import java.lang.reflect.Method;

import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import net.sf.cglib.proxy.NoOp;

/**
 * @author longe 拦截器
 */
public class TDaoCglibProxy implements MethodInterceptor {

	private String name;
	private Object objT;

	public TDaoCglibProxy(String name) {
		this.name = name;
	}

	public TDaoCglibProxy(Object obj, String name) {
		this.name = name;
		this.objT = obj;
	}

//	@Override
	public Object intercept(Object obj, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
//		if (!name.equals("张三")) {
//			System.out.println("没有权限!");
//			return null;
//		}

		System.out.println("方法执行之前");
		Object ob = proxy.invokeSuper(obj, args);
		System.out.println("方法执行之后");
		// return method.invoke(objT, args); //通过反射进行调用
		return ob; // 使用Cglib代理调用
	}

	public static void main(String[] args) {
		//下边这句生成class文件到 第二个参数的目录里
		System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\\\classes");
		Enhancer en = new Enhancer();
		en.setSuperclass(TDao.class);
		TDaoCglibProxy callBack = new TDaoCglibProxy("张三1");
		// 指定两个callback，通过callBackFilter返回的下标值控制调用使用那一个callback处理
//		Callback[] ss = new Callback[]{ callBack };
//		en.setCallback(NoOp.INSTANCE);
//		en.setCallback(callBack);
		en.setCallbacks(new Callback[] { NoOp.INSTANCE, callBack });
		// 方法过滤器，根据过滤器返回不同的值回调对应下标的Callback方法
		en.setCallbackFilter(new TDaoCglibFilter());
		TDao dao = (TDao) en.create();
		dao.create();
		dao.query();
		dao.update();
		dao.delete();
	}

}
